<script setup>
import { computed } from 'vue'
import prop from './props'
const props = defineProps(prop)
defineOptions({
  name: 'LeePager',
})
const emit = defineEmits(['page-change'])
const pager = computed(() => {
  let renderPager = []
  if (props.total <= props.pagerCount) {
    // 总页数小于可见页码
    for (let index = 1; index <= props.total; index++) {
      renderPager.push(index)
    }
  } else {
    // 总页数大于可见页码
    if (props.currentPage <= 5) {
      for (let index = 1; index <= 5; index++) {
        renderPager.push(index)
      }
    } else if (props.currentPage >= props.total - 4) {
      for (let index = props.total - 4; index <= props.total; index++) {
        renderPager.push(index)
      }
    } else {
      for (
        let index = props.currentPage - 2;
        index <= props.currentPage + 2;
        index++
      ) {
        renderPager.push(index)
      }
    }
  }
  return renderPager
})
const pageChange = page => {
  if (page <= 0) {
    page = 1
  } else if (page >= props.total) {
    page = props.total
  }
  emit('page-change', page)
}
</script>

<template>
  <div
    class="lee-pager"
    :class="{
      [`lee-pager--${type}`]: type,
      [`lee-pager--${size}`]: size,
    }"
  >
    <!-- 首页和上一页 -->
    <a
      :class="currentPage === 1 ? 'disabled' : ''"
      @click.prevent="pageChange(1)"
      >首页</a
    >
    <a
      :class="currentPage === 1 ? 'disabled' : ''"
      @click.prevent="pageChange(currentPage - 1)"
    >
      <lee-icon icon="angles-left"></lee-icon>
    </a>
    <!-- 中间 -->
    <a
      v-if="total > pagerCount && currentPage > 5"
      @click.prevent="pageChange(1)"
      >1</a
    >
    <a v-if="total > pagerCount && currentPage > 5">
      <lee-icon icon="ellipsis" size="sm"></lee-icon>
    </a>
    <a
      @click.prevent="pageChange(page)"
      v-for="page in pager"
      :key="page"
      :class="{ active: currentPage === page }"
      >{{ page }}</a
    >
    <a v-if="total > pagerCount && currentPage < total - 4">
      <lee-icon icon="ellipsis" size="sm"></lee-icon>
    </a>
    <a
      v-if="total > pagerCount && currentPage < total - 4"
      @click.prevent="pageChange(total)"
      >{{ total }}</a
    >
    <!-- 尾页和下一页 -->
    <a
      :class="currentPage === total ? 'disabled' : ''"
      @click.prevent="pageChange(currentPage + 1)"
    >
      <lee-icon icon="angles-right"></lee-icon>
    </a>
    <a
      :class="currentPage === total ? 'disabled' : ''"
      @click.prevent="pageChange(total)"
      >尾页</a
    >
  </div>
</template>
